/**
 *  created by jsq on 2017/9/22
 */
import React from 'react';
import { connect } from 'react-redux'
import menuRoute from 'routes/menuRoute'
import { Form, Button, Row, Icon, Table, message, Checkbox  } from 'antd'
import {messages} from "share/common";
import budgetService from 'containers/budget-setting/budget-organization/budget-item/budget-item.service'
import ListSelector from 'components/list-selector'
import BasicInfo from 'components/basic-info'
import 'styles/budget-setting/budget-organization/budget-item/budget-item-detail.scss';
import LanguageInput from 'components/template/language-input/language-input';

const FormItem = Form.Item;

class BudgetItemDetail extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      loading: true,
      buttonLoading: false,
      companyListSelector: false,  //控制公司选则弹框
      budgetItem:{},
      data: [],
      edit: false,
      visible: false,
      pagination: {
        current: 1,
        page: 0,
        total:0,
        pageSize:10,
        showSizeChanger:true,
        showQuickJumper:true,
      },
      infoList: [
        {type: 'input', id: 'organizationName', isRequired: true, disabled: true, label: messages('budget-setting.key47'/*预算组织*/)+" :" /*预算组织*/},
        {type: 'input', id: 'itemCode', isRequired: true, disabled: true, label: messages('budget-setting.key44'/*预算项目代码*/)+" :" /*预算项目代码*/},
        {type: 'select',options: [] , id: 'itemTypeName', required:true, disabled: true, label:"预算项目类型："},
        {type: 'switch', id: 'isEnabled', label: messages('common.column.status') +" :"/*状态*/},
      ],
      extraInfo: [
        {type: 'input', id: 'itemName', isRequired:true, label: messages('budget-setting.key45'/*预算项目名称*/) +" :"/*预算项目名称*/},
        {type: 'input', id: 'description', label: messages('budget-setting.key55'/*备注*/) +" :"/*预算项目描述*/},
      ],

      columns: [
        {title: messages('budget-setting.key56'/*公司代码*/), key: 'companyCode', dataIndex: 'companyCode'},/*公司代码*/
        {title: messages('budget-setting.key57'/*公司名称*/), key: 'companyName', dataIndex: 'companyName'}, /*公司明称*/
        {                        /*启用*/
          title:messages('common.status.enable'), key: "doneRegisterLead", dataIndex: 'doneRegisterLead',width:'10%',
          render: (isEnabled, record) => <Checkbox onChange={(e) => this.onChangeEnabled(e, record)} checked={record.isEnabled}/>
        },
      ],
      i18n: {}
    }
  }

  //改变启用状态
  onChangeEnabled = (e, record) => {
    this.setState({loading: true});
    record.isEnabled = e.target.checked;
    budgetService.updateItemAssignedCompany(record).then((response) => {
      this.getList()
    })
  };

  componentWillMount(){
    //根据路径上的id,查出该条预算项目完整数据
    budgetService.getItemById(this.props.params.itemId).then((response)=>{
      if(response.status === 200){
        response.data.itemTypeName = {label:response.data.itemTypeName,value:response.data.itemTypeName};
        response.data.variationAttribute = {label:response.data.variationAttributeName,value:response.data.variationAttribute};
        this.setState({
          budgetItem: response.data,
          i18n: response.data.i18n || {},
          description:response.data.description,
          itemName: response.data.itemName
        })
      }
    });
    this.getList();
  }


  //保存所做的详情修改
  handleUpdate = (value) => {
    const { budgetItem: { organizationId, id, versionNumber }, i18n, description, itemName  } = this.state;
    budgetService.updateItem({
      ...value,
      ...{
        organizationId,
        id,
        versionNumber,
        i18n,
        description,
        itemName
      }
    })
      .then((response) => {
      if(response) {
        response.data.organizationName = this.state.budgetItem.organizationName;
        response.data.itemTypeName = { label: value.itemTypeName, value: value.itemTypeName };
        message.success(messages('budget-setting.key31'/*保存成功！*/)); /*保存成功！*/
        this.setState({
          budgetItem: response.data,
          edit: true
        }, () => this.handleEdit(false))
      }
    })
  };

  //查询已经分配过的公司
  getList(){
    const {pagination} = this.state;
    budgetService.itemAssignedCompany({itemId:this.props.params.itemId,page:pagination.page,size:pagination.pageSize}).then((response)=>{
      response.data.map((item)=>{
        item.key= item.id
      });
      if(response.status === 200){
        let pagination = this.state.pagination;
        pagination.total = Number(response.headers['x-total-count']);
        this.setState({
          loading: false,
          data: response.data,
          pagination
        })
      }
    })
  }


  //控制是否编辑
  handleEdit = (flag) => {
    this.setState({edit: flag})
  };

  //控制是否弹出公司列表
  showListSelector = (flag) =>{
    this.setState({
      companyListSelector: flag
    })
  };

  //处理公司弹框点击ok,分配公司
  handleListOk = (result) => {
    if(result.result.length>0){
      let companyIds = [];
      let resourceIds = [];
      resourceIds.push(this.props.params.itemId);
      result.result.map((item)=>{
        companyIds.push(item.id)
      });
      let param = [];
      param.push({"companyIds": companyIds, "resourceIds": resourceIds});
      budgetService.batchAddCompanyToItem(param).then((response)=>{
        if(response.status === 200){
          message.success(`${messages('common.operate.success')}`);
          this.setState({
            loading: true,
            companyListSelector: false,
          },this.getList())
        }
      }).catch((e)=>{
        if(e.response){
          message.error(`${messages('common.operate.filed')},${e.response.data.message}`)
        }
      });
    }else
      this.showListSelector(false);
  };

  //返回预算项目
  handleBack = () => {
    this.context.router.push(menuRoute.getMenuItemByAttr('budget-organization', 'key').children.budgetOrganizationDetail.url.replace(':id', this.props.params.id)+ '?tab=ITEM');
  };

  //分页点击
  onChangePager = (pagination,filters, sorter) =>{
    let temp = this.state.pagination;
    temp.page = pagination.current-1;
    temp.current = pagination.current;
    temp.pageSize = pagination.pageSize;
    this.setState({
      loading: true,
      pagination: temp
    }, ()=>{
      this.getList();
    })
  };

  handleI18n = (name, value, tag) => {
    let { i18n, itemName, description } = this.state;
    if (tag === 'input') {
      i18n.itemName = value;
      itemName = name;
    } else {
      i18n.description = value;
      description = name;
    }
    this.setState({ itemName, description, i18n });
  };

  renderExtraFields = () => {
    const { i18n, extraInfo } = this.state;
    const { form: { getFieldDecorator } } = this.props;
    return extraInfo.map(item =>
      <FormItem label={item.label}>
        {getFieldDecorator(item.id, {
          initialValue: this.state[item.id],
          rules: [{
            required: item.isRequired,
            message: messages('common.can.not.be.empty', { name: item.label }),  //name 不可为空
          }]
        })(
          <LanguageInput
            key={item.id}
            isEdit={true}
            i18nName={i18n[item.id] || null}
            nameChange={(name, value) => this.handleI18n(name, value, item.id === 'itemName' ? 'input' : 'textArea')}
            placeholder={messages('common.please.enter')/* 请输入 */}
            mainLanguageIsRequired={!!item.isRequired}/>
        )}
      </FormItem>
    );
  };

  render(){
    const { loading, edit, pagination, columns, data, extraInfo, infoList, budgetItem, companyListSelector } = this.state;
    return(
      <div className="budget-item-detail">
        <BasicInfo
          infoList={infoList}
          infoData={budgetItem}
          extraFields={this.renderExtraFields()}
          extraFieldsIndex={2}
          extraInfo={extraInfo}
          updateHandle={this.handleUpdate}
          updateState={edit}/>
        <div className="table-header">
          <div className="table-header-title">{messages('common.total',{total:`${pagination.total}`})}</div>  {/*共搜索到*条数据*/}
          <div className="table-header-buttons">
            <Button type="primary" onClick={()=>this.showListSelector(true)}>{messages('budget-setting.key59'/*添加公司*/)}</Button>  {/*添加公司*/}
          </div>
        </div>
        <Table
          loading={loading}
          dataSource={data}
          columns={columns}
          pagination={pagination}
          onChange={this.onChangePager}
          size="middle"
          bordered/>
        <a style={{fontSize:'14px',paddingBottom:'20px'}} onClick={this.handleBack}><Icon type="rollback" style={{marginRight:'5px'}}/>{messages('common.back')}</a>
        <ListSelector
          type="company_item"
          visible={companyListSelector}
          onOk={this.handleListOk}
          extraParams={{ itemId: this.props.params.itemId }}
          onCancel={() => this.showListSelector(false)}/>
      </div>)
  }
}
BudgetItemDetail.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    organization: state.budget.organization
  }
}

const WrappedBudgetItemDetail = Form.create()(BudgetItemDetail);

export default connect(mapStateToProps)(WrappedBudgetItemDetail);

